﻿namespace dotnet_notes.Tools
{
    /// <summary>
    /// 导出工具类
    /// </summary>
    public static class ExportTool
    {
        /// <summary>
        /// 转换成 Excel 文件流
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataList">要转换的集合对象</param>
        /// <param name="headers">标题数组</param>
        /// <param name="addSerialNumber">是否添加序号列(默认是)</param>
        /// <returns></returns>
        public static Stream ToExcel<T>
            (List<T> dataList, List<string> headers, bool addSerialNumber = true)
        {
            var workbook = new XSSFWorkbook();
            var sheet = workbook.CreateSheet("Sheet1");

            // 标题行
            IRow headerRow = sheet.CreateRow(0);
            if (addSerialNumber) headers.Insert(0, "序号");

            for (int i = 0; i < headers.Count; i++)
            {
                headerRow.CreateCell(i).SetCellValue(headers[i]);
            }

            if (dataList != null && dataList.Count != 0)
            {
                var firstItem = dataList[0] ?? throw new InvalidOperationException();
                PropertyInfo[] properties = firstItem.GetType().GetProperties();

                // 数据行
                for (int i = 0; i < dataList.Count; i++)
                {
                    IRow row = sheet.CreateRow(i + 1);
                    if (addSerialNumber) row.CreateCell(0).SetCellValue(i + 1);

                    T item = dataList[i];

                    for (int j = 0; j < properties.Length; j++)
                    {
                        int cellIndex = addSerialNumber ? j + 1 : j;
                        object? value = properties[j].GetValue(item, null);
                        row.CreateCell(cellIndex).SetCellValue(value?.ToString() ?? "");
                    }
                }
            }

            var stream = new MemoryStream();
            workbook.Write(stream, true);
            stream.Position = 0;

            return stream;
        }
    }
}
